<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门票名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入门票名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 部门卡片展示区域 -->
    <div v-if="loading" class="loading-container">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>

    <div v-else-if="deptTickets.length === 0" class="no-data">
      <el-empty description="暂无门票数据"></el-empty>
    </div>

    <div v-else class="card-container">
      <div v-for="(dept, index) in deptTickets" :key="index" class="dept-card">
        <div class="dept-header">
          <i class="el-icon-office-building"></i>
          <span class="ticket-count">{{ dept.tickets.length }} 种门票</span>
        </div>

        <el-carousel :interval="4000" height="240px" indicator-position="outside">
          <el-carousel-item v-for="(ticket, idx) in dept.tickets" :key="idx">
            <div class="carousel-item">
              <div class="ticket-image">
                <image-preview :src="ticket.imageUrl" :width="150" :height="150"/>
              </div>
              <div class="ticket-info">
                <h3>{{ ticket.name }}</h3>
                <p><span class="label">价格:</span> ¥{{ ticket.price }}</p>
                <p><span class="label">有效期:</span> {{ ticket.validDays }}天</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>

        <div class="card-actions">
          <el-button type="primary" size="mini" @click="viewDeptDetail(dept)">
            <i class="el-icon-view"></i> 查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 部门详情对话框 -->
    <!-- 部门详情对话框 - 修改部分开始 -->
    <el-dialog
      :title="'部门ID: ' + currentDept.deptId + ' 的门票详情'"
      :visible.sync="detailDialogVisible"
      width="80%"
      top="5vh"
    >
      <div class="detail-container">
        <div v-for="(ticket, index) in currentDept.tickets" :key="index" class="ticket-detail-card">
          <div class="ticket-header">
            <div class="ticket-title">
              <span class="ticket-name">{{ ticket.name }}</span>
              <el-tag type="success" size="mini">¥{{ ticket.price }}</el-tag>
              <el-tag type="info" size="mini">{{ ticket.validDays }}天有效</el-tag>
            </div>
            <div class="ticket-actions">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleUpdate(ticket)"
              >修改</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(ticket)"
              >删除</el-button>
            </div>
          </div>

          <div class="ticket-body">
            <div class="ticket-image">
              <image-preview :src="ticket.imageUrl" :width="180" :height="180"/>
            </div>
            <div class="ticket-description">
              <h4>门票描述</h4>
              <p>{{ ticket.description || '暂无描述信息' }}</p>
              <div class="ticket-meta">
                <p><span class="label">门票名称:</span> {{ ticket.name }}</p>
                <p><span class="label">创建时间:</span> {{ ticket.createTime }}</p>
              </div>
            </div>
          </div>

          <!-- 新增：加入购物车操作区域 -->
          <div class="ticket-cart">
            <div class="cart-controls">
              <span class="cart-label">购买数量:</span>
              <el-input-number
                v-model="ticket.quantity"
                :min="0"
                :max="10"
                size="small"
                @change="handleQuantityChange(ticket)"
              ></el-input-number>
              <el-button
                type="success"
                size="small"
                icon="el-icon-shopping-cart"
                @click="addToCart(ticket)"
                class="add-cart-btn"
              >
                加入购物车
              </el-button>
            </div>
            <div class="cart-total">
              小计: <span class="total-price">¥{{ (ticket.price * ticket.quantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改门票产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入所属部门ID" />
        </el-form-item>
        <el-form-item label="门票名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入门票名称" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="validDays">
          <el-input v-model="form.validDays" placeholder="请输入有效期天数" type="number">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="门票描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" rows="4" />
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listTicket, getTicket, delTicket, addTicket, updateTicket ,addToCart} from "@/api/system/ticket"

  export default {
    name: "Ticket",
    data() {
      return {
        cartItems: [],//新增购物车
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 按部门分组后的门票数据
        deptTickets: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 部门详情对话框
        detailDialogVisible: false,
        // 当前查看详情的部门
        currentDept: {
          deptId: '',
          tickets: []
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptId: null,
          name: null,
          price: null,
          validDays: null,
          description: null,
          imageUrl: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deptId: [
            { required: true, message: "所属部门ID不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "门票名称不能为空", trigger: "blur" }
          ],
          price: [
            { required: true, message: "单价不能为空", trigger: "blur" },
            { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的价格格式", trigger: "blur" }
          ],
          validDays: [
            { required: true, message: "有效期天数不能为空", trigger: "blur" },
            { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" }
          ]
        }
      }
    },
    created() {
      this.userId = this.$store.state.id;
      this.queryParams.userId = this.userId;
      this.getList()
    },
    methods: {
      // 处理数量变化
      handleQuantityChange(ticket) {
        ticket.quantity = Math.max(0, Math.min(10, ticket.quantity));
      },
      // 加入购物车
      addToCart(ticket) {
        if (ticket.quantity <= 0) {
          this.$message.error("请选择购买数量");
          return;
        }

        const cartData = {
          userId: this.userId,
          productId: ticket.id,
          productType: "门票",
          deptId: ticket.deptId,
          quantity: ticket.quantity,
          unitPrice: ticket.price,
          totalPrice: (ticket.price * ticket.quantity).toFixed(2)
        };

        // 调用加入购物车API
        addToCart(cartData).then(response => {
          this.$message.success("已加入购物车");
          // 重置数量
          ticket.quantity = 0;
        }).catch(error => {
          this.$message.error("加入购物车失败: " + error.message);
        });
         },
      /** 查询门票产品列表 */
      getList() {
        this.loading = true
        listTicket(this.queryParams).then(response => {
          // 将门票按部门分组
          this.groupTicketsByDept(response.rows)
        this.total = response.total
        this.loading = false
      }).catch(() => {
          this.loading = false
      })
      },

      /** 按部门分组门票 */
      groupTicketsByDept(tickets) {
        const deptMap = {}

        tickets.forEach(ticket => {
          const deptId = ticket.deptId
          if (!deptMap[deptId]) {
          deptMap[deptId] = {
            deptId: deptId,
            tickets: []
          }
        }
        deptMap[deptId].tickets.push(ticket)
      })

        // 转换为数组并排序
        this.deptTickets = Object.values(deptMap).sort((a, b) => a.deptId - b.deptId)
      },

      /** 查看部门详情 */
      viewDeptDetail(dept) {
        this.currentDept = dept
        this.detailDialogVisible = true
      },

      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },

      // 表单重置
      reset() {
        this.form = {
          id: null,//门票id
          deptId: null,
          name: null,
          price: null,
          validDays: null,
          description: null,
          imageUrl: null,
          createTime: null
        }
        this.resetForm("form")
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加门票产品"
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id
        getTicket(id).then(response => {
          this.form = response.data
        this.open = true
        this.title = "修改门票产品"
      })
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateTicket(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
            } else {
              addTicket(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
            }
          }
        })
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id
        this.$modal.confirm('是否确认删除门票产品 "' + row.name + '"?').then(() => {
          return delTicket(id)
        }).then(() => {
          this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('system/ticket/export', {
          ...this.queryParams
      }, `ticket_${new Date().getTime()}.xlsx`)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    padding: 20px;
    background-color: #f5f7fa;
  }

  .card-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
    gap: 20px;
    margin-top: 20px;
  }

  .dept-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    transition: transform 0.3s, box-shadow 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    }
  }

  .dept-header {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    background: linear-gradient(135deg, #409EFF, #64b5ff);
    color: white;
    font-size: 16px;

    .el-icon-office-building {
      font-size: 20px;
      margin-right: 10px;
    }

    .dept-name {
      font-weight: 600;
      flex: 1;
    }

    .ticket-count {
      background: rgba(255, 255, 255, 0.2);
      padding: 3px 10px;
      border-radius: 12px;
      font-size: 13px;
    }
  }

  .carousel-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    height: 100%;

    .ticket-image {
      margin-bottom: 15px;

      ::v-deep .el-image {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .ticket-info {
      text-align: center;

      h3 {
        margin: 0 0 10px;
        font-size: 18px;
        color: #303133;
      }

      p {
        margin: 5px 0;
        font-size: 14px;
        color: #606266;

        .label {
          font-weight: 600;
          color: #409EFF;
        }
      }
    }
  }

  .card-actions {
    padding: 15px 20px;
    text-align: center;
    border-top: 1px solid #ebeef5;

    .el-button {
      width: 100%;
    }
  }

  .detail-container {
    max-height: 65vh;
    overflow-y: auto;
    padding: 10px;
  }

  .ticket-detail-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    margin-bottom: 20px;
    padding: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .ticket-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 15px;

    .ticket-title {
      display: flex;
      align-items: center;

      .ticket-name {
        font-size: 18px;
        font-weight: 600;
        margin-right: 12px;
        color: #303133;
      }

      .el-tag {
        margin-right: 8px;
      }
    }
  }

  .ticket-body {
    display: flex;

    .ticket-image {
      flex: 0 0 180px;
      margin-right: 20px;

      ::v-deep .el-image {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .ticket-description {
      flex: 1;

      h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #409EFF;
        font-size: 16px;
      }

      p {
        line-height: 1.6;
        color: #606266;
        margin-bottom: 15px;
      }

      .ticket-meta {
        display: flex;
        gap: 20px;
        font-size: 14px;
        color: #909399;

        .label {
          font-weight: 600;
          color: #67C23A;
          margin-right: 5px;
        }
      }
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;

    .el-icon-loading {
      font-size: 40px;
      color: #409EFF;
      margin-bottom: 15px;
    }
  }

  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
  }

  .el-carousel__item {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  ::v-deep .el-carousel__button {
    width: 10px;
    height: 10px;
    border-radius: 50%;
  }

  .ticket-cart {
    margin-top: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #ebeef5;

    .cart-controls {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .cart-label {
        margin-right: 15px;
        font-weight: 600;
        color: #606266;
      }

      .el-input-number {
        margin-right: 15px;
        width: 120px;
      }

      .add-cart-btn {
        background: linear-gradient(135deg, #67C23A, #85ce61);
        border-color: #67C23A;
        color: white;

        &:hover {
          opacity: 0.9;
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }

    .cart-total {
      text-align: right;
      font-size: 16px;
      color: #606266;

      .total-price {
        font-weight: bold;
        color: #e6a23c;
        font-size: 18px;
        margin-left: 5px;
      }
    }
  }

  /* 调整门票详情卡片间距 */
  .ticket-detail-card {
    margin-bottom: 25px;
  }
</style>
